﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace WordpressRestApi
{
    /// <summary>Client for the tag API.</summary>
    /// <remarks>See https://developer.wordpress.com/docs/api/ for the endpoints available.</remarks>
    public class TagClient : ApiClientBase
    {
        #region Inner Types
        private class TagPayload
        {
            [JsonProperty("found")]
            public int Found { get; set; }

            [JsonProperty("tags")]
            public TagInfo[] Tags { get; set; }
        }
        #endregion

        /// <summary>Constructor.</summary>
        /// <param name="token"></param>
        internal TagClient(TokenInfo token)
            : base(token)
        {
        }

        /// <summary>Returns all the tags of the associated site.</summary>
        /// <remarks>
        /// See https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/tags/
        /// </remarks>
        /// <returns>Asynchronous enumerable of tags.</returns>
        public IAsyncEnumerable<TagInfo> GetAllTags()
        {
            const int PAGE_SIZE = 200;
            var startUrl = API_ROOT + "sites/" + Token.BlogID + "/tags?number=" + PAGE_SIZE;

            return new ApiAsyncEnumerable<TagInfo, TagPayload>(
                Token,
                startUrl + "&page=1",
                (payload) => payload.Tags,
                (payload, page) => payload.Found > PAGE_SIZE * (page + 1),
                (payload, page) => startUrl + "&page=" + (page + 1));
        }

        /// <summary>Deletes a given tag in the associated site.</summary>
        /// <remarks>
        /// See https://developer.wordpress.com/docs/api/1.1/post/sites/%24site/tags/slug:%24tag/delete/
        /// </remarks>
        /// <param name="tagSlug">Slug of the tag to delete.</param>
        /// <returns>Tag information.</returns>
        public async Task<TagInfo> DeleteTagAsync(string tagSlug)
        {
            var url = API_ROOT + "sites/" + Token.BlogID + "/tags/slug:" + tagSlug + "/delete";
            var info = await PostRequestAsync<TagInfo>(url);

            return info;
        }
    }
}